package com.ywy.service.impl;

import com.ywy.dao.CommentDao;
import com.ywy.entity.Comment;
import com.ywy.service.CommentService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * 评论Service实现类
 *
 * @author ywy
 * @date 2022/9/8 17:18
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Resource
    private CommentDao commentDao;

    @Override
    public List<Comment> list(Comment comment, Integer page, Integer pageSize) {
        Pageable pageable = new PageRequest(page - 1, pageSize, Sort.Direction.DESC, "createDate");
        Page<Comment> pageArticle = commentDao.findAll(createSpecification(comment), pageable);
        return pageArticle.getContent();
    }

    @Override
    public long getTotal(Comment comment) {
        return commentDao.count(createSpecification(comment));
    }

    @Override
    public Comment getById(Integer id) {
        return commentDao.findOne(id);
    }

    @Override
    public Comment save(Comment comment) {
        return commentDao.save(comment);
    }

    @Override
    public void delete(Integer id) {
        commentDao.delete(id);
    }

    private Specification createSpecification(Comment comment) {
        return (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (comment != null) {
                if (comment.getStatus() != null) {
                    list.add(criteriaBuilder.equal(root.get("status"), comment.getStatus()));
                }
                if (comment.getRes() != null && comment.getRes().getId() != null) {
                    list.add(criteriaBuilder.equal(root.get("res").get("id"), comment.getRes().getId()));
                }
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };
    }
}
